package com.cheyunkeji.er.fragment.evaluate;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.EvaluateWorkflowActivity;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.utils.StrUtil;
import com.cheyunkeji.er.view.SDialog;
import com.cheyunkeji.er.view.SToast;
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

/** Created by Michael on 2017/4/10 20:26. */
public class CheckResultPz extends BaseFragment
    implements EvaluateWorkflowActivity.OnOutActionListener, SDialog.SDialog2Listener {

  public static final int PAGE_INDEX = 14;
  private static final String TAG = CheckResultPz.class.getSimpleName();

  @BindView(R.id.tv_upload_report)
  TextView tvUploadReport;

  @BindView(R.id.iv_star1)
  ImageView ivStar1;

  @BindView(R.id.rb_accident_yes)
  RadioButton rbAccidentYes;

  @BindView(R.id.rb_accident_no)
  RadioButton rbAccidentNo;

  @BindView(R.id.rg_accident)
  RadioGroup rgAccident;

  @BindView(R.id.iv_star2)
  ImageView ivStar2;

  @BindView(R.id.rb_hs_yes)
  RadioButton rbHsYes;

  @BindView(R.id.rb_hs_no)
  RadioButton rbHsNo;

  @BindView(R.id.rg_hsc)
  RadioGroup rgHsc;

  @BindView(R.id.iv_star3)
  ImageView ivStar3;

  @BindView(R.id.rb_spc_yes)
  RadioButton rbSpcYes;

  @BindView(R.id.rb_spc_no)
  RadioButton rbSpcNo;

  @BindView(R.id.rg_spc)
  RadioGroup rgSpc;

  @BindView(R.id.et_value_price)
  EditText etValuePrice;

  @BindView(R.id.et_evaluate_conclusion)
  EditText etEvaluateConclusion;

  private SDialog dialog;

  @Override
  protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {

    contentView = inflater.inflate(R.layout.er_frag_check_result_pz, container, false);
    ButterKnife.bind(this, contentView);
  }

  @Override
  protected void init() {}

  @Override
  protected void initView() {

    tvUploadReport.setOnClickListener(this);
    ((EvaluateWorkflowActivity) getActivity())
        .setTitleDesc(StrUtil.getString(R.string.check_pizhu));
    rgHsc.clearCheck();
    rgSpc.clearCheck();
    rgAccident.clearCheck();

    //        如果是已上传待编辑评估类型，则隐藏上传按钮
    if (((EvaluateWorkflowActivity) getActivity()).getEvaluateArchiveType()
        == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {
      tvUploadReport.setVisibility(View.GONE);
    }

    displayInfo();
  }

  private void displayInfo() {

    if (null != MyApplication.getInstance().getEvaluateResult()) {

      if (MyApplication.getInstance().getEvaluateResult().getIsacc() == 1) {
        rgAccident.check(R.id.rb_accident_yes);
      } else if (MyApplication.getInstance().getEvaluateResult().getIsacc() == 0) {
        rgAccident.check(R.id.rb_accident_no);
      }

      if (MyApplication.getInstance().getEvaluateResult().getIsburn() == 1) {
        rgHsc.check(R.id.rb_hs_yes);
      } else if (MyApplication.getInstance().getEvaluateResult().getIsburn() == 0) {
        rgHsc.check(R.id.rb_hs_no);
      }

      if (MyApplication.getInstance().getEvaluateResult().getIsws() == 1) {
        rgSpc.check(R.id.rb_spc_yes);
      } else if (MyApplication.getInstance().getEvaluateResult().getIsws() == 0) {
        rgSpc.check(R.id.rb_spc_no);
      }

      //            rgAccident.check(MyApplication.getEvaluateResult().getIsacc() == 1 ?
      // R.id.rb_accident_yes : R.id.rb_accident_no);
      //            rgHsc.check(MyApplication.getEvaluateResult().getIsburn() == 1 ? R.id.rb_hs_yes
      // : R.id.rb_hs_no);
      //            rgSpc.check(MyApplication.getEvaluateResult().getIsws() == 1 ? R.id.rb_spc_yes :
      // R.id.rb_spc_no);

      //            if( !TextUtils.isEmpty(MyApplication.getEvaluateResult().getRefprice()) && 0 !=
      // Float.valueOf(MyApplication.getEvaluateResult().getRefprice()))
      //            etValuePrice.setText(MyApplication.getEvaluateResult().getRefprice());

      etEvaluateConclusion.setText(MyApplication.getInstance().getEvaluateResult().getVerdict());
    }
  }

  @Override
  protected void initData() {}

  @Override
  public void onClick(View v) {
    super.onClick(v);
    switch (v.getId()) {
      case R.id.tv_upload_report:
        onSaveEvaluateResult(
            new Runnable() {
              @Override
              public void run() {
                uploadEvaluateReport();
              }
            });
        break;
      default:
        break;
    }
  }

  private void uploadEvaluateReport() {

    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("aid", MyApplication.getInstance().getEvaluateResult().getAid());

    ApiClient.postForm(
        HttpConstants.UP_TO_ARCHIVE_INFO,
        params,
        new StringCallback() {

          @Override
          public void onError(Call call, Exception e, int id) {
            // 网络异常
            if (e instanceof UnknownHostException || e instanceof SocketException) {
              SToast.show(R.string.tip_network_error, Gravity.CENTER);
              return;
            }
          }

          @Override
          public void onResponse(String response, int id) {
            Log.e(TAG, "onResponse: 检查结果批注： " + response);
            try {
              final JSONObject obj = new JSONObject(response);
              if (1 == obj.optInt("code", 0)) {
                SToast.show("上传成功！");
                MyApplication.getInstance().clearEvaluateResult();
                CheckResultPz.this.getActivity().finish();
              } else {
                if(dialog!=null){
                  dialog.dismiss();
                  dialog = null;
                }
                if (null == dialog) {
//                  dialog =
//                      new SDialog(
//                          CheckResultPz.this.getActivity(),
//                          R.string.t_message_title,
//                          obj.optString("msg"),
//                          CheckResultPz.this,
//                          SDialog.TYPE_1_BTN);
                  dialog =
                      new SDialog(
                          CheckResultPz.this.getActivity(),
                          "温馨提示",
                          obj.optString("msg"),
                          R.string.t_supplement,
                          R.string.t_cancel,
                          new SDialog.SDialog2Listener() {
                            @Override
                            public void onClick(boolean l, View view) {
                              //true：左按钮 false：右按钮
                              if (l) {
                                // 发送通知给主页面检测为填写完成的界面
                                EventBus.getDefault().post(obj);
                              }
                            }
                          });
                  dialog.show();
                }
//                else {
//                  dialog.setContent(obj.optString("msg"));
//
//                }
//                dialog.show();
              }

            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        });
  }

  private Runnable mTask;

  @Override
  public void onSaveEvaluateResult(Runnable task) {
    if (task != null) {
      mTask = task;
    }
    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("aid", MyApplication.getInstance().getEvaluateResult().getAid());
    params.put("isacc", rgAccident.getCheckedRadioButtonId() == R.id.rb_accident_yes ? "1" : "0");
    params.put("isburn", rgHsc.getCheckedRadioButtonId() == R.id.rb_hs_yes ? "1" : "0");
    params.put("isws", rgSpc.getCheckedRadioButtonId() == R.id.rb_spc_yes ? "1" : "0");
    //        params.put("refprice", etValuePrice.getText().toString());
    params.put("verdict", etEvaluateConclusion.getText().toString());

    if (MyApplication.getInstance().getEvaluateResult() == null
        || MyApplication.getInstance().getEvaluateResult().getIroute() == null
        || MyApplication.getInstance().getEvaluateResult().getIroute().size() == 0) {
      int[] iroute = new int[15];
      iroute[PAGE_INDEX] = 1;
      String json = new Gson().toJson(iroute);
      Log.e(TAG, "saveData: 评估记录为空或数组为空时 保存记录数组 ：  " + json.substring(1, json.length() - 1));
      params.put("iroute", json.substring(1, json.length() - 1));
    } else {
      MyApplication.getInstance().getEvaluateResult().getIroute().set(PAGE_INDEX, 1);
      String json = new Gson().toJson(MyApplication.getInstance().getEvaluateResult().getIroute());
      params.put("iroute", json.substring(1, json.length() - 1));
      Log.e(
          TAG, "saveData:  保存记录数组 ：记录非空并且数组非空时 保存记录数组 ：   " + json.substring(1, json.length() - 1));
    }

    for (String keySet : params.keySet()) {
      Log.e(
          TAG,
          "====================== onSaveEvaluateResult: key : ========================="
              + keySet
              + "\t   value : "
              + params.get(keySet));
    }

    //        根据评估类型进行保存或编辑
    int evaluateType = ((EvaluateWorkflowActivity) getActivity()).getEvaluateArchiveType();

    //       保存新创建、未上传待评估数据
    if (evaluateType == Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE
        || evaluateType == Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE
        || evaluateType == Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN) {

      ApiClient.postForm(
          ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(),
          params,
          new RespCallback<EvaluateDetailResult2>() {

            @Override
            protected void onRequestFailed(String msg) {
              SToast.show(msg);
              if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                mTask.run();
                mTask = null;
              }
            }

            @Override
            protected void onSuccess(EvaluateDetailResult2 data) {
              if (null != data) {
                MyApplication.getInstance().setEvaluateResult(data);
                if (mTask != null) {
                  mTask.run();
                  mTask = null;
                }
              }
            }

            @Override
            public void onBefore(Request request, int id) {
              showDialog();
            }

            @Override
            public void onAfter(int id) {
              dismissDialog();
            }
          });
    } else if (evaluateType == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {
      ApiClient.postForm(
          ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(),
          params,
          new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
              // 网络异常
              if (e instanceof UnknownHostException || e instanceof SocketException) {
                SToast.show(R.string.tip_network_error, Gravity.CENTER);
                return;
              }
            }

            @Override
            public void onResponse(String response, int id) {

              try {
                JSONObject obj = new JSONObject(response);
                if (obj.optInt("code") == 1) {
                  Log.e(TAG, "onResponse: 编辑成功 : " + obj.optString("data"));
                  if (mTask != null) {
                    mTask.run();
                    mTask = null;
                  }
                } else {
                  SToast.show(obj.optString("msg"));
                  if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                    mTask.run();
                    mTask = null;
                  }
                }
              } catch (JSONException e) {
                e.printStackTrace();
              }
            }

            @Override
            public void onBefore(Request request, int id) {
              showDialog();
            }

            @Override
            public void onAfter(int id) {
              dismissDialog();
            }
          });
    }
  }

  @Override
  public void onClick(boolean l, View view) {

  }
}
